<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
        @toLoadMethods="toLoadMethods"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
      <span class="table-col-select-container">
      <div class="table-title"><div style="float: left">城市对比分析信息</div></div>
      <div class="top-button-list">
         <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
      </div>
      </span>
        <el-table
          :data="tableData"
          :span-method="mergeMethod"
          v-if="tableMainHeight>0"
          :fit="true"
          :border="true"
          :stripe="true"
          :cell-style="{ borderColor:'#f0f0f0',padding: 5 }"
          :header-cell-style="{ borderColor:'#f0f0f0', backgroundColor: '#FAFAFA' }"
          :show-header="true"
          style="width: 100%"
          :max-height = "tableMainHeight"
          v-loading="loading"
        >
          <el-table-column
            v-for="(item, index) in tableColumn"
            :prop="item.prop"
            :label="item.label"
            :align="item.align"
            :width="item.minWidth"
            :key="index"
          >
            <template slot-scope="scope">
              <!--暂时限制满意度类型，后续等产研修改同步调整-->
              <span v-if="item.prop=='threeTargetName' && curCheckType!=3"
                    class="threeTargetName_c"
                    @click="showDetail(scope.row)">{{scope.row.threeTargetName}}</span>
              <span v-else>{{scope.row[item.prop]}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--指标树弹框-->
    <TargetDialog
      :dialog-visible="targetDialogShow"
      @close="targetEditClose"
      @success="targetEditSuccess"
      :title="targetTitle"
      :year="searchData.form.year"
    ></TargetDialog>
    <!--详情-->
    <detailDialog :dialog-visible="detailDialogShow"
                  @close="editClose"
                  :openType="detailOpenType"
                  :threeTargetNo="threeTargetNo"
                  :title="detailTitle"
                  :year="year"
                  :resultType="resultType"
                  :cityCheckTypeOptions = "cityCheckTypeOptions"
                  :showHistoryChars="true"
    ></detailDialog>
  </div>
</template>

<script>
  import { contrastAnalysis,
    contrastAnalysisExport,
  } from '@/api/risk/cityWaringResult'
  import { getAreaList } from '@/api/system/area'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import TargetDialog from '@/views/xy/public/cityAnalysis/components/targetDialog'
  import detailDialog from '@/views/xy/public/cityAnalysis/indicatorDiagnosis/detail'
  export default {
    components:{
      SearchForm,ButtonForm,TargetDialog,detailDialog
    },
    data(){
      return{
        curCheckType:1,
        baseColumns:[
          {
            prop: 'oneTargetName',
            label: '指标分类一',
            minWidth: '150',
            slotname: 'oneTargetName',
            options: {}
          },
          {
            prop: 'twoTargetName',
            label: '指标分类二',
            minWidth: '150',
            slotname: 'twoTargetName',
            options: {}
          },
          {
            prop: 'threeTargetName',
            label: '指标名称',
            minWidth: '220',
            slotname: 'threeTargetName',
            options: {}
          },
          {
            prop: 'scalar',
            label: '对标值',
            minWidth: '80',
            slotname: 'scalar',
            options: {}
          },
          {
            prop: 'avg',
            label: '平均数',
            minWidth: '80',
            slotname: 'avg',
            options: {}
          },
          {
            prop: 'medium',
            label: '中位数',
            minWidth: '80',
            slotname: 'medium',
            options: {}
          },
        ],
        tableColumn:[],
        tableData:[],
        selection: [],
        loading:false,
        total:1,
        pageNum:1,
        pageSize:10,
        dict:{},
        searchData:{
          form:{
            cityCode:['0'],
            year:new Date().getFullYear()+'',
            targetName:'',
            targetCode:'',
            targetType:'',
            resultType:'',
            checkType:1
          },
          options:[
            {
              title:'年份',
              key: "year",
              type: "dateYear",
            },
            {
              title:'体检分类',
              key: "checkType",
              type: "select",
              multiple:false,
              option: {
                data: this.cityCheckTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title:'评价结果类型',
              key: "resultType",
              type: "select",
              multiple:false,
              option: {
                data: this.cityCheckResultTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title:'城市',
              key: "cityCode",
              type: "select",
              multiple:true,
              option: {
                data: this.cityList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "areaName", // 指定label对应data的字段
                  value: "areaCode", // 指定value对应data的字段
                },
              },
            },
            {
              title:'指标分类',
              key: "targetName",
              type: "clickText",
              event:"openTreeDialog"
            }
          ]
        },
        buttonList:[
          {name:'导出数据',methods:'handleExport', type:'primary', hasPremission:["contrastAnalysis:export"]}
        ],
        tableMainHeight: 0,
        // 字典
        cityCheckTypeOptions:[],
        cityCheckResultTypeOptions: [],
        cityList:[],
        // 合并存储
        mergeFirstColumn:[],
        firstColumnIndex:0,
        mergeSecondColumn:[],
        secondColumnIndex:0,
        targetDialogShow:false,
        targetTitle:"选择体检指标",
        detailDialogShow:false,
        detailOpenType:"add",
        threeTargetNo:"",
        detailTitle:"新增",
        year:"",
        resultType:"",
      }
    },
    watch: {
      'cityList':{
        handler(newVal, oldVal){
          if(newVal){
            this.searchData.options.forEach(t=>{
              if(t.key == 'cityCode'){
                t.option.data = newVal
              }
            })
          }
        }
      },
      'cityCheckTypeOptions':{
        handler(newVal, oldVal){
          if(newVal){
            this.searchData.options.forEach(t=>{
              if(t.key == 'checkType'){
                t.option.data = newVal
              }
            })
          }
        }
      },
      'cityCheckResultTypeOptions':{
        handler(newVal, oldVal){
          if(newVal){
            console.log("jieg1leix1",newVal)
            // 移除达标类型选择
            newVal = newVal.filter(t=>t.name!="standard")
            this.searchData.options.forEach(t=>{
              if(t.key == 'resultType'){
                t.option.data = newVal
              }
            })
          }
        }
      }
    },
    methods:{
      editClose(){
        this.detailDialogShow = false
      },
      showDetail(row){
         console.log("show======>", row)
        this.detailDialogShow = false
        this.threeTargetNo = row.threeTargetNo
        this.year = this.searchData.form.year
        this.resultType= 'rate'
        this.detailOpenType = "detail"
        this.detailTitle="详情"
        this.detailDialogShow = true
      },
      targetEditClose(){
         this.targetDialogShow =false
      },
      targetEditSuccess(data){
        // 处理值
        console.log("获取值",data)
        this.searchData.form.targetName = data.targetName
        this.searchData.form.targetCode = data.targetCode,
        this.searchData.form.targetType = data.targetType
        this.targetEditClose()
      },
      // 遍历每一行数据判断合并几行（仅对一二列）
      formatMergeData() {
        // 重置
        this.mergeFirstColumn = [];
        this.firstColumnIndex = 0;
        this.mergeSecondColumn = [];
        this.secondColumnIndex = 0;
        for (let i = 0; i < this.tableData.length; i++) {
          if (i == 0) {
            this.mergeFirstColumn.push(1);
            this.mergeSecondColumn.push(1);
          } else {
            if ( this.tableData[i]["oneTargetName"] == this.tableData[i - 1]["oneTargetName"]) {
              this.mergeFirstColumn[this.firstColumnIndex] += 1;
              this.mergeFirstColumn.push(0);
              if (this.tableData[i]["twoTargetName"] ==  this.tableData[i - 1]["twoTargetName"]) {
                this.mergeSecondColumn[this.secondColumnIndex] += 1;
                this.mergeSecondColumn.push(0);
              } else {
                this.mergeSecondColumn.push(1);
                this.secondColumnIndex = i;
              }
            } else {
              this.mergeFirstColumn.push(1);
              this.firstColumnIndex = i;
              this.mergeSecondColumn.push(1);
              this.secondColumnIndex = i;
            }
          }
        }
      },
      mergeMethod({ row, column, rowIndex, columnIndex }) {
          // 合并第一列
          if (columnIndex == 0) {
            let rowSpan = this.mergeFirstColumn[rowIndex];
            return {
              rowspan: rowSpan,
              colspan: rowSpan > 0 ? 1 : 0,
            };
          }
          // 合并第二列
          if (columnIndex == 1) {
            let rowSpan = this.mergeSecondColumn[rowIndex];
            return {
              rowspan: rowSpan,
              colspan: rowSpan > 0 ? 1 : 0,
            };
          }
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      openTreeDialog(){
        console.log("打开弹框===========>")
        this.targetDialogShow = true
      },
      search(){
        this.fetch({
          ...this.searchData.form,
        })
      },
      async setTempData() {
        let cityCode = this.searchData.form.cityCode
        let item = cityCode.find(t => t == '0')
        let tempData = {cityCode:"",cityName:"",column:[]}
        let tempCity = this.cityList
        if (this.cityList.length == 0) {
          let res = await getAreaList({parentCode: "440000000000"})
          tempCity = res.data
        }
        if (item != undefined) {
          tempData.column =  tempCity.filter(t => t.areaCode != '0').map(x => {
            return {prop: x.areaCode, label: x.areaName, minWidth: '100', slotname: x.areaCode};
          })
          tempData.cityCode = tempData.column.map(t=>t.prop).join(",")
          tempData.cityName = tempData.column.map(t=>t.label).join(",")
          return tempData;
        }
        tempData.column = tempCity.filter(t => cityCode.indexOf(t.areaCode) != -1).map(x => {
          return {prop: x.areaCode, label: x.areaName, minWidth: '100', slotname: x.areaCode};
        })
        tempData.cityCode = tempData.column.map(t=>t.prop).join(",")
        tempData.cityName = tempData.column.map(t=>t.label).join(",")
        return tempData;
      },
      async fetch(params={}){
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        params.targetName = ''
        if( this.searchData.form.cityCode.length==0){
          this.$message.warning("请选择查询城市")
          return
        }
        this.curCheckType = params.checkType
        let tempData = await this.setTempData()
        console.log("temp=====>",tempData)
        params.cityCode = tempData.cityCode
        this.loading = true
        contrastAnalysis(params).then(res=>{
          if(res.code==200){
            this.tableColumn = this.baseColumns.concat(tempData.column)
            this.tableData = res.data
            this.formatMergeData()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData(){
        this.searchData.form = {
          cityCode:['0'],
          year:new Date().getFullYear()+'',
          targetName:'',
          targetCode:'',
          targetType:'',
          resultType:'',
          checkType:1
        }
        this.curCheckType = 1
      },
      // 触发按钮区域按钮方法
      clickButton(methods){
        this[methods]()
      },
     async handleExport(){
        if( this.searchData.form.cityCode.length==0){
          this.$message.warning("请选择查询城市")
          return
        }
        let tempData = await this.setTempData()
        let params = {
          ...this.searchData.form,
          cityCode:tempData.cityCode,
          cityName:tempData.cityName
        }
        params.targetName = ''
        contrastAnalysisExport(params,`城市对比分析_${new Date().getTime()}.xlsx`);
      },
    },
    activated(){
      this.fetch({ cityCode:['0'], year:new Date().getFullYear()+'', checkType:this.searchData.form.checkType})
    },
    created(){
      // 获取字典值
      this.cityCheckTypeOptions = []
      this.$commonJs.filterDataDict("cityCheckType",this.cityCheckTypeOptions)
      this.cityCheckResultTypeOptions = []
      this.$commonJs.filterDataDict("cityCheckResultType",this.cityCheckResultTypeOptions)
      getAreaList({parentCode:"440000000000"}).then(res=>{
        if(res.code==200){
          this.cityList = res.data
          this.cityList.unshift({areaCode:"0",areaName:"全部"})
        }
      })
      this.$commonJs.setLeftMenuHidden(this)
    },
    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

    .search-box {
      padding-bottom: 6px;
    }

    .table-box {
      padding-top: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;

      .table-main {
        flex: 1;
        overflow: auto;
        .threeTargetName_c {
           cursor: pointer;
           color: rgb(42,146,253);
        }
        .threeTargetName_c:hover{
          border-bottom: 1px solid rgb(42,146,253);
        }

        //-----------------------------
        ::v-deep .el-table th{
          padding: 10px 0;
        }
        ::v-deep .el-table td{
          padding: 8px 0;
        }
        .table-col-select-container{
          // float: right;
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .table-title{
            font-size: 16px;
          }
        }
        .table-col-select-list-container {
          // 让每一个单选按钮单行排版 并具有一定的边距
          ::v-deep .el-checkbox {
            display: block;
            margin: 5px 10px;
          }
        }
        .top-button-list{
          display: flex;
          align-items: baseline;
        }


        // 2023.9.9 按运管服的样式进行了修改 ----------------开始-------------------------
        .btn_content{
          margin-bottom: 0px;
        }
        ::v-deep .el-dropdown{
          font-size: 20px;
          top: 2px;
          cursor: pointer;
        }
        // 2023.9.9 按运管服的样式进行了修改 ----------------结束-------------------------

      }

      .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
      }

      ::v-deep .pagination-container {
        text-align: right;
      }

   }
  }
</style>
